package com.java9s.goldchit.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;

import org.springframework.orm.hibernate3.HibernateTemplate;

import com.java9s.goldchit.beans.Chit;

public class ChitDaoImpl implements ChitDao {
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Chit getChit(int chitId) {
		Chit c = (Chit) getSessionFactory().getCurrentSession().get(Chit.class,
				Integer.valueOf(chitId));
		return c;
	}

	@Override
	public List getAllChits() {
		Criteria criteria = getSessionFactory().getCurrentSession()
				.createCriteria(Chit.class);
		List chits = criteria.list();
		return chits;
	}

	@Override
	public void saveChit(Chit chit) {
		if (chit != null) {
			getSessionFactory().getCurrentSession().save(chit);
		}

	}

	@Override
	public void updateChit(Chit chit) {
		if (chit != null) {
			getSessionFactory().getCurrentSession().saveOrUpdate(chit);
		}

	}

	@Override
	public void markChitAsDelete(Chit chit) {
		if (chit != null && chit.isDeleted() == true) {
			Chit dbChit = this.getChit(chit.getChitNumber());
			dbChit.setDeleted(true);
			getSessionFactory().getCurrentSession().saveOrUpdate(chit);
		} else {
			// Ignore the change
		}

	}

}
